<template>
  <div class="notification-settings">
    <h2 class="settings-title">通知设置</h2>
    
    <!-- 浏览器通知设置 -->
    <div class="settings-section">
      <h3 class="section-title">浏览器通知</h3>
      <div class="setting-item">
        <div class="setting-info">
          <span class="setting-label">启用浏览器通知</span>
          <span class="setting-description">接收天文事件的实时通知提醒</span>
        </div>
        <div class="setting-control">
          <button 
            v-if="!notificationService.hasPermission()"
            class="primary-button"
            @click="requestBrowserPermission"
          >
            {{ browserPermissionText }}
          </button>
          <div v-else class="permission-granted">
            <span class="check-icon">✓</span>
            <span>已启用</span>
          </div>
        </div>
      </div>
      
      <div class="setting-item">
        <div class="setting-info">
          <span class="setting-label">默认提前提醒时间</span>
          <span class="setting-description">设置事件开始前多久收到提醒</span>
        </div>
        <div class="setting-control">
          <select v-model="defaultReminderTime" class="select-control">
            <option :value="15">15分钟</option>
            <option :value="30">30分钟</option>
            <option :value="60">1小时</option>
            <option :value="120">2小时</option>
            <option :value="1440">1天</option>
          </select>
        </div>
      </div>
    </div>
    
    <!-- 邮件通知设置 -->
    <div class="settings-section">
      <h3 class="section-title">邮件通知</h3>
      <div class="setting-item">
        <div class="setting-info">
          <span class="setting-label">启用邮件提醒</span>
          <label class="switch">
            <input type="checkbox" v-model="emailPreferences.enabled">
            <span class="slider"></span>
          </label>
        </div>
      </div>
      
      <div class="setting-item" v-if="emailPreferences.enabled">
        <div class="setting-info">
          <span class="setting-label">邮箱地址</span>
          <span class="setting-description">用于接收提醒邮件</span>
        </div>
        <div class="setting-control">
          <input 
            type="email" 
            v-model="userEmail" 
            class="input-control"
            placeholder="your@email.com"
          />
          <button 
            class="secondary-button"
            @click="saveEmail"
            :disabled="!isValidEmail"
          >
            保存
          </button>
        </div>
        <div v-if="emailSaveMessage" class="message" :class="emailSaveMessageType">
          {{ emailSaveMessage }}
        </div>
      </div>
      
      <div class="setting-item" v-if="emailPreferences.enabled && userEmail">
        <div class="setting-info">
          <span class="setting-label">提醒频率</span>
          <span class="setting-description">选择接收邮件提醒的频率</span>
        </div>
        <div class="setting-control">
          <div class="radio-group">
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="emailPreferences.reminderFrequency" 
                value="immediate"
              >
              <span>即时提醒（每个事件单独通知）</span>
            </label>
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="emailPreferences.reminderFrequency" 
                value="daily"
              >
              <span>每日汇总</span>
            </label>
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="emailPreferences.reminderFrequency" 
                value="weekly"
              >
              <span>每周汇总</span>
            </label>
          </div>
        </div>
      </div>
      
      <div class="setting-item" v-if="emailPreferences.enabled && userEmail">
        <div class="setting-info">
          <span class="setting-label">事件类型</span>
          <span class="setting-description">选择要接收提醒的事件类型</span>
        </div>
        <div class="setting-control">
          <div class="checkbox-group">
            <label class="checkbox-option">
              <input 
                type="checkbox" 
                v-model="emailPreferences.eventTypes" 
                value="meteorShower"
              >
              <span>流星雨</span>
            </label>
            <label class="checkbox-option">
              <input 
                type="checkbox" 
                v-model="emailPreferences.eventTypes" 
                value="eclipse"
              >
              <span>日月食</span>
            </label>
            <label class="checkbox-option">
              <input 
                type="checkbox" 
                v-model="emailPreferences.eventTypes" 
                value="planet"
              >
              <span>行星冲日/合相</span>
            </label>
            <label class="checkbox-option">
              <input 
                type="checkbox" 
                v-model="emailPreferences.eventTypes" 
                value="comet"
              >
              <span>彗星</span>
            </label>
          </div>
        </div>
      </div>
      
      <div class="setting-item" v-if="emailPreferences.enabled && userEmail">
        <div class="setting-control">
          <button class="secondary-button" @click="testEmail">
            发送测试邮件
          </button>
          <div v-if="testEmailMessage" class="message" :class="testEmailMessageType">
            {{ testEmailMessage }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 当前提醒列表 -->
    <div class="settings-section" v-if="activeReminders.length > 0">
      <h3 class="section-title">当前设置的提醒</h3>
      <div class="reminders-list">
        <div v-for="reminder in activeReminders" :key="reminder.id" class="reminder-item">
          <div class="reminder-info">
            <h4 class="reminder-title">{{ reminder.eventTitle }}</h4>
            <p class="reminder-details">
              事件时间: {{ formatDate(reminder.eventDate) }}<br>
              提醒时间: {{ formatDate(reminder.reminderTime) }} (提前 {{ reminder.minutesBefore }} 分钟)
            </p>
          </div>
          <button 
            class="danger-button"
            @click="removeReminder(reminder.id)"
          >
            取消提醒
          </button>
        </div>
      </div>
    </div>
    
    <div class="settings-actions">
      <button class="primary-button" @click="savePreferences">
        保存所有设置
      </button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import notificationService from '../services/NotificationService'
import emailNotificationService from '../services/EmailNotificationService'

export default {
  name: 'NotificationSettings',
  setup() {
    // 浏览器通知服务
    const notificationServiceRef = notificationService;
    
    // 邮件通知服务
    const emailNotificationServiceRef = emailNotificationService;
    
    // 浏览器通知相关状态
    const browserPermissionText = ref('请求通知权限');
    const defaultReminderTime = ref(60); // 默认提前1小时提醒
    
    // 邮件通知相关状态
    const userEmail = ref('');
    const emailPreferences = reactive(emailNotificationServiceRef.emailPreferences);
    const emailSaveMessage = ref('');
    const emailSaveMessageType = ref('success');
    const testEmailMessage = ref('');
    const testEmailMessageType = ref('success');
    
    // 计算属性
    const isValidEmail = computed(() => {
      return emailNotificationServiceRef.validateEmail(userEmail.value);
    });
    
    const activeReminders = computed(() => {
      return notificationServiceRef.getAllReminders();
    });
    
    // 方法
    const requestBrowserPermission = async () => {
      browserPermissionText.value = '请求中...';
      const granted = await notificationServiceRef.requestPermission();
      
      if (granted) {
        browserPermissionText.value = '已授权';
      } else {
        browserPermissionText.value = '授权失败，请在浏览器设置中手动开启';
      }
    };
    
    const saveEmail = () => {
      if (!isValidEmail.value) {
        emailSaveMessage.value = '请输入有效的邮箱地址';
        emailSaveMessageType.value = 'error';
        return;
      }
      
      const success = emailNotificationServiceRef.saveUserEmail(userEmail.value);
      if (success) {
        emailSaveMessage.value = '邮箱地址已保存';
        emailSaveMessageType.value = 'success';
      } else {
        emailSaveMessage.value = '保存失败，请稍后重试';
        emailSaveMessageType.value = 'error';
      }
      
      // 3秒后清除消息
      setTimeout(() => {
        emailSaveMessage.value = '';
      }, 3000);
    };
    
    const savePreferences = () => {
      // 保存邮件偏好设置
      emailNotificationServiceRef.saveEmailPreferences(emailPreferences);
      
      // 保存默认提醒时间
      localStorage.setItem('defaultReminderTime', defaultReminderTime.value.toString());
      
      // 显示保存成功消息（可以在这里添加一个全局消息组件）
      console.log('所有设置已保存');
    };
    
    const removeReminder = (reminderId) => {
      notificationServiceRef.removeReminder(reminderId);
    };
    
    const testEmail = async () => {
      if (!isValidEmail.value) {
        testEmailMessage.value = '请先设置有效的邮箱地址';
        testEmailMessageType.value = 'error';
        return;
      }
      
      const result = await emailNotificationServiceRef.testEmail();
      if (result.success) {
        testEmailMessage.value = result.message;
        testEmailMessageType.value = 'success';
      } else {
        testEmailMessage.value = result.error;
        testEmailMessageType.value = 'error';
      }
      
      // 5秒后清除消息
      setTimeout(() => {
        testEmailMessage.value = '';
      }, 5000);
    };
    
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    // 组件挂载时加载数据
    onMounted(() => {
      // 加载用户邮箱
      userEmail.value = emailNotificationServiceRef.userEmail || '';
      
      // 加载默认提醒时间
      const savedTime = localStorage.getItem('defaultReminderTime');
      if (savedTime) {
        defaultReminderTime.value = parseInt(savedTime);
      }
    });
    
    return {
      notificationService: notificationServiceRef,
      browserPermissionText,
      defaultReminderTime,
      userEmail,
      emailPreferences,
      isValidEmail,
      emailSaveMessage,
      emailSaveMessageType,
      testEmailMessage,
      testEmailMessageType,
      activeReminders,
      requestBrowserPermission,
      saveEmail,
      savePreferences,
      removeReminder,
      testEmail,
      formatDate
    };
  }
};
</script>

<style scoped>
.notification-settings {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.settings-title {
  font-size: 28px;
  margin-bottom: 30px;
  color: #ffffff;
  text-align: center;
}

.settings-section {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  backdrop-filter: blur(10px);
}

.section-title {
  font-size: 22px;
  margin-bottom: 20px;
  color: #ffffff;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 10px;
}

.setting-item {
  margin-bottom: 20px;
}

.setting-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.setting-label {
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
}

.setting-description {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 5px;
}

.setting-control {
  margin-top: 10px;
}

/* 按钮样式 */
.primary-button {
  background-color: #4a6fa5;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.primary-button:hover {
  background-color: #3a598a;
}

.secondary-button {
  background-color: transparent;
  color: #4a6fa5;
  border: 1px solid #4a6fa5;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.secondary-button:hover {
  background-color: #4a6fa5;
  color: white;
}

.danger-button {
  background-color: #ff4d4d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.danger-button:hover {
  background-color: #cc0000;
}

/* 输入控件样式 */
.input-control {
  width: 100%;
  padding: 10px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 16px;
  margin-bottom: 10px;
}

.input-control:focus {
  outline: none;
  border-color: #4a6fa5;
  box-shadow: 0 0 0 2px rgba(74, 111, 165, 0.3);
}

.select-control {
  width: 100%;
  padding: 10px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 16px;
}

.select-control:focus {
  outline: none;
  border-color: #4a6fa5;
  box-shadow: 0 0 0 2px rgba(74, 111, 165, 0.3);
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #4a6fa5;
}

input:focus + .slider {
  box-shadow: 0 0 1px #4a6fa5;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

/* 单选框和复选框组 */
.radio-group,
.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-option,
.checkbox-option {
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  cursor: pointer;
}

.radio-option input[type="radio"],
.checkbox-option input[type="checkbox"] {
  width: 18px;
  height: 18px;
  accent-color: #4a6fa5;
}

/* 提醒列表 */
.reminders-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.reminder-item {
  background-color: rgba(255, 255, 255, 0.05);
  padding: 15px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reminder-title {
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 10px;
}

.reminder-details {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
}

/* 状态指示器 */
.permission-granted {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4CAF50;
  font-weight: 500;
}

.check-icon {
  font-size: 18px;
}

/* 消息样式 */
.message {
  margin-top: 10px;
  padding: 10px;
  border-radius: 6px;
  font-size: 14px;
}

.message.success {
  background-color: rgba(76, 175, 80, 0.2);
  color: #4CAF50;
}

.message.error {
  background-color: rgba(244, 67, 54, 0.2);
  color: #F44336;
}

/* 设置操作按钮 */
.settings-actions {
  text-align: center;
  margin-top: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-settings {
    padding: 15px;
  }
  
  .settings-section {
    padding: 20px;
  }
  
  .setting-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .reminder-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .reminder-item > button {
    align-self: flex-end;
  }
}
</style>